<template>
    <div>
        <!-- https://github.com/davidroyer/vue2-editor 
            :editorToolbar 指定工具类
        -->
        <el-button type="primary" @click="submit" :loading="isLoadingDesc">提交</el-button>
        <vue-editor id="editor"
      useCustomImageHandler
      @imageAdded="handleImageAdded" v-model="htmlForEditor">
    </vue-editor>
    </div>
</template>

<script>
import { VueEditor } from "vue2-editor";
import gooItemApi from "../../api/gooItemApi";
import {commonApi} from "../../api/api.js";
import strUtils from "../../utils/strUtils";
import axios from 'axios'

export default {
  data: function() {
    return {
      baseResDownUrl: null,//资源获取url
      isLoadingDesc: false,
      htmlForEditor: "<h3>Hi,my girl</h3>",
      gooItemId: null
    };
  },
  components: {
    VueEditor
  },
  mounted: function() {
    this.gooItemId = this.$store.state.gooItem.gooItem.id;
    this.loadData(this.gooItemId);
    this.baseResDownUrl = commonApi.retrieveFileUrl('');
  },
  methods: {
    handleImageAdded: function(file, Editor, cursorLocation) {//添加图片资源
      var formData = new FormData();
      formData.append("files", file);
     axios({
          url: commonApi.uploadFilesUrlCompress(1200,600),
          method: 'POST',
          data: formData
        })
        .then(res => {
          console.log("文件上传res:", res);
          let imageUrl = this.baseResDownUrl + res.data[0]; // Get url from response
          console.log('image-url：',imageUrl)
          Editor.insertEmbed(cursorLocation, "image", imageUrl);
        })
        .catch(err => {
          this.$notify.error({
            title: "上传文件失败",
            message: err.errors_msg
          });
        });
    },
    loadData(gooItemId) {
      if (gooItemId) {
        gooItemApi
          .getOne(gooItemId)
          .then(res => {
            const desc = res.data.itemDesc;
            if (desc && desc != "null") {
              this.htmlForEditor = strUtils.escapeAndRmQuote(decodeURIComponent(desc));
            }
          })
          .catch(err => {
            this.$notify.error({
              title: "获取内容失败",
              message: err.errors_msg
            });
          });
      }
    },
    submit() {
      this.isLoadingDesc = true;
      gooItemApi
        .updateDesc(this.gooItemId, { itemDesc: encodeURIComponent(this.htmlForEditor) })
        .then(res => {
          if (res.status == 200) {
            this.$notify({
              title: "成功",
              message: "详情提交成功",
              type: "success"
            });
            this.$emit("retrieve-cur-step", 2);
            this.isLoadingDesc = false;
          }
        })
        .catch(err => {
          this.$notify.error({
            title: "提交失败",
            message: err.errors_msg
          });
          this.isLoadingDesc = false;
        });
    }
  },
  computed: {
    editor() {
      return this.$refs.myTextEditor.quillEditor;
    }
  }
};
</script>
